package com.nantes.nantourage.dao;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.nantes.nantourage.utils.FileHelper;

public class DataBaseHelper extends SQLiteOpenHelper {

    // The Android's default system path of your application database.
    /**
     * Le chemin vers la base de donn�es de l'application dans le smartphone
     */
    private static String DB_PATH = "/data/data/com.nantes.nantourage/databases/";

    /**
     * Le nom de la base de données
     */
    private static String DB_NAME = "nantourage_db";

    /**
     * Le version de la base de données
     */
    private static int DB_VERSION = 1000;

    /**
     * L'objet base de donnée récupérée sur le smartphone
     */
    private SQLiteDatabase myDatabase;

    /**
     * Le contexte de l'application
     */
    private final Context myContext;

    private boolean isPreloadDataFinished = false;

    public boolean isPreloadDataFinished() {
        return isPreloadDataFinished;
    }

    private boolean upgradeCalled;

    private boolean createCalled;

    /**
     * Constructor Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * 
     * @param context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     */
    public void createDataBase() throws IOException {

        myDatabase = getReadableDatabase();
        myDatabase.close();

        // la base n'existait pas on copie la version embarquée
        if(createCalled) {
            try {
                copyDataBase();
            } catch (Exception e) {
                throw new Error("Error copying database");
            }
        }

        // la version de la base a changée on effectue un annuler/remplace de la BDD
        if(upgradeCalled) {
            try {
                deleteDataBase();
                copyDataBase();
            } catch (Exception e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the system folder, from where it can be accessed and handled. This is done by transfering bytestream.
     */
    private void copyDataBase() throws Exception {

        // Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        FileHelper.copyFile(myInput, new File(DB_PATH, DB_NAME));

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

    @Override
    public synchronized void close() {
        if(myDatabase != null)
            myDatabase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        createCalled = true;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        upgradeCalled = true;
    }

    public void deleteDataBase() {
        String myPath = DB_PATH + DB_NAME;
        File database = new File(myPath);
        database.delete();
    }

}